package santeclair.referentiel.webservice.rest.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import santeclair.lunar.framework.cache.dto.AdminCache;
import santeclair.lunar.framework.cache.util.CacheUtils;
import santeclair.lunar.framework.cache.webservice.AdminCacheManagerWebservice;

@Service("referentielCacheManagerWebservice")
public class ReferentielCacheManagerWebserviceImpl implements AdminCacheManagerWebservice {
    
    @Autowired
    private EhCacheCacheManager cacheManager;
    
    /**
     * {@inheritDoc}
     */
    @Override
    public List<AdminCache> listCaches() {
        List<AdminCache> adminCaches = new ArrayList<>();
        for (String cacheName : cacheManager.getCacheNames()) {
            AdminCache adminCache = CacheUtils.createAdminCache(cacheManager.getCache(cacheName));
            adminCaches.add(adminCache);
        }
        return adminCaches;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public AdminCache clearCache(String name) {
        Cache cache = cacheManager.getCache(name);
        if (cache != null) {
            AdminCache adminCache = CacheUtils.clearCache(cache);
            return adminCache;
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<AdminCache> clearAllCache() {
        List<AdminCache> adminCaches = new ArrayList<>();
        for (String cacheName : cacheManager.getCacheNames()) {
            AdminCache adminCache = CacheUtils.clearCache(cacheManager.getCache(cacheName));
            adminCaches.add(adminCache);
        }
        return adminCaches;
    }
    
    
}
